import React, { useState, useEffect } from 'react';
import { Container, Table, Button, Alert, Modal, Form, Card } from 'react-bootstrap';
import { useNavigate } from 'react-router-dom';
import UserService from '../services/UserService';
import AuthService from '../services/AuthService';

const AdminDashboard = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [currentUser, setCurrentUser] = useState(null);
  const [editForm, setEditForm] = useState({
    email: '',
    fullName: '',
    enabled: true
  });
  
  const navigate = useNavigate();

  useEffect(() => {
    // 验证是否为管理员
    const user = AuthService.getCurrentUser();
    console.log('AdminDashboard - 当前用户:', user);
    
    // 检查角色是直接在user对象上还是在user.user中
    let isAdmin = false;
    if (user) {
      if (user.role === 'ROLE_ADMIN') {
        isAdmin = true;
      } else if (user.user && user.user.role === 'ROLE_ADMIN') {
        isAdmin = true;
      }
    }
    
    if (!isAdmin) {
      console.log('不是管理员，重定向到登录页');
      navigate('/login');
      return;
    }
    
    // 加载用户列表
    loadUsers();
  }, [navigate]);

  const loadUsers = () => {
    setLoading(true);
    console.log('开始加载用户列表');
    UserService.getAllUsers()
      .then(response => {
        console.log('获取用户列表响应:', response);
        if (response.data && response.data.data) {
          setUsers(response.data.data);
        }
        setLoading(false);
      })
      .catch(error => {
        console.error('获取用户列表错误:', error.response || error);
        setError('获取用户列表失败: ' + (error.response?.data?.message || error.message || '未知错误'));
        setLoading(false);
      });
  };

  const handleDeleteClick = (user) => {
    setCurrentUser(user);
    setShowDeleteModal(true);
  };

  const handleEditClick = (user) => {
    setCurrentUser(user);
    setEditForm({
      email: user.email || '',
      fullName: user.fullName || '',
      enabled: user.enabled
    });
    setShowEditModal(true);
  };

  const handleDelete = () => {
    if (!currentUser) return;
    
    UserService.deleteUser(currentUser.id)
      .then(() => {
        setShowDeleteModal(false);
        loadUsers();
      })
      .catch(error => {
        setError('删除用户失败');
        console.error('Error deleting user:', error);
      });
  };

  const handleEditFormChange = (e) => {
    const { name, value, checked } = e.target;
    setEditForm({
      ...editForm,
      [name]: name === 'enabled' ? checked : value
    });
  };

  const handleEdit = () => {
    if (!currentUser) return;
    
    const updatedUser = {
      ...currentUser,
      ...editForm
    };
    
    UserService.updateUser(currentUser.id, updatedUser)
      .then(() => {
        setShowEditModal(false);
        loadUsers();
      })
      .catch(error => {
        setError('更新用户失败');
        console.error('Error updating user:', error);
      });
  };

  return (
    <Container fluid className="mt-4 px-5">
      <div className="d-flex justify-content-between align-items-center mb-4">
        <h2 className="mb-0" style={{ color: '#2e7d32', fontWeight: '600', fontSize: '1.75rem' }}>管理员控制面板</h2>
        <div className="d-flex gap-2">
          <Button 
            variant="outline-success"
            onClick={() => window.location.reload()}
            style={{
              borderColor: '#2e7d32',
              color: '#2e7d32',
              fontWeight: '500',
              display: 'flex',
              alignItems: 'center',
              gap: '8px',
              padding: '0.5rem 1rem',
              fontSize: '1rem'
            }}
          >
            <i className="bi bi-arrow-clockwise"></i>
            刷新数据
          </Button>
        </div>
      </div>
      
      {error && (
        <Alert variant="danger" className="mb-4" style={{ borderRadius: '8px', fontSize: '1rem' }}>
          {error}
        </Alert>
      )}
      
      {loading ? (
        <div className="text-center py-5">
          <div className="spinner-border text-success" role="status" style={{ width: '3rem', height: '3rem' }}>
            <span className="visually-hidden">加载中...</span>
          </div>
          <p className="mt-3 text-muted" style={{ fontSize: '1.1rem' }}>正在加载用户数据...</p>
        </div>
      ) : (
        <Card className="shadow-sm" style={{ border: 'none', borderRadius: '12px' }}>
          <Card.Body className="p-0">
            <div className="table-responsive">
              <Table hover className="mb-0">
                <thead style={{ backgroundColor: '#f8f9fa' }}>
                  <tr>
                    <th style={{ padding: '1.25rem', fontWeight: '600', color: '#495057', fontSize: '1rem' }}>ID</th>
                    <th style={{ padding: '1.25rem', fontWeight: '600', color: '#495057', fontSize: '1rem' }}>用户名</th>
                    <th style={{ padding: '1.25rem', fontWeight: '600', color: '#495057', fontSize: '1rem' }}>电子邮箱</th>
                    <th style={{ padding: '1.25rem', fontWeight: '600', color: '#495057', fontSize: '1rem' }}>姓名</th>
                    <th style={{ padding: '1.25rem', fontWeight: '600', color: '#495057', width: '140px', textAlign: 'center', fontSize: '1rem' }}>角色</th>
                    <th style={{ padding: '1.25rem', fontWeight: '600', color: '#495057', width: '140px', textAlign: 'center', fontSize: '1rem' }}>状态</th>
                    <th style={{ padding: '1.25rem', fontWeight: '600', color: '#495057', width: '180px', textAlign: 'center', fontSize: '1rem' }}>操作</th>
                  </tr>
                </thead>
                <tbody>
                  {users.map(user => (
                    <tr key={user.id} style={{ borderBottom: '1px solid #e9ecef' }}>
                      <td style={{ padding: '1.25rem', verticalAlign: 'middle', fontSize: '1rem' }}>{user.id}</td>
                      <td style={{ padding: '1.25rem', verticalAlign: 'middle', fontWeight: '500', fontSize: '1rem' }}>{user.username}</td>
                      <td style={{ padding: '1.25rem', verticalAlign: 'middle', fontSize: '1rem' }}>{user.email || '-'}</td>
                      <td style={{ padding: '1.25rem', verticalAlign: 'middle', fontSize: '1rem' }}>{user.fullName}</td>
                      <td style={{ padding: '1.25rem', verticalAlign: 'middle', textAlign: 'center' }}>
                        <span className={`badge ${user.role === 'ROLE_ADMIN' ? 'bg-success' : 'bg-secondary'}`} 
                              style={{ padding: '0.6em 1em', fontSize: '0.9rem', minWidth: '100px', display: 'inline-block' }}>
                          {user.role === 'ROLE_ADMIN' ? '管理员' : '普通用户'}
                        </span>
                      </td>
                      <td style={{ padding: '1.25rem', verticalAlign: 'middle', textAlign: 'center' }}>
                        <span className={`badge ${user.enabled ? 'bg-success' : 'bg-danger'}`}
                              style={{ padding: '0.6em 1em', fontSize: '0.9rem', minWidth: '100px', display: 'inline-block' }}>
                          {user.enabled ? '激活' : '禁用'}
                        </span>
                      </td>
                      <td style={{ padding: '1.25rem', verticalAlign: 'middle', textAlign: 'center' }}>
                        <div className="d-flex justify-content-center" style={{ gap: '12px', minWidth: '160px' }}>
                          <Button 
                            variant="outline-success" 
                            size="sm"
                            onClick={() => handleEditClick(user)}
                            style={{
                              borderColor: '#2e7d32',
                              color: '#2e7d32',
                              fontWeight: '500',
                              padding: '0.5rem 1rem',
                              fontSize: '0.95rem',
                              width: '100px'
                            }}
                          >
                            <i className="bi bi-pencil me-1"></i>
                            编辑
                          </Button>
                          {user.role !== 'ROLE_ADMIN' && (
                            <Button 
                              variant="outline-danger" 
                              size="sm"
                              onClick={() => handleDeleteClick(user)}
                              style={{
                                fontWeight: '500',
                                padding: '0.5rem 1rem',
                                fontSize: '0.95rem',
                                width: '100px'
                              }}
                            >
                              <i className="bi bi-trash me-1"></i>
                              删除
                            </Button>
                          )}
                          {user.role === 'ROLE_ADMIN' && (
                            <div style={{ width: '100px' }}></div>
                          )}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </Table>
            </div>
          </Card.Body>
        </Card>
      )}

      {/* 删除确认对话框 */}
      <Modal show={showDeleteModal} onHide={() => setShowDeleteModal(false)} centered size="lg">
        <Modal.Header closeButton style={{ borderBottom: '1px solid #e9ecef', padding: '1.25rem' }}>
          <Modal.Title style={{ color: '#dc3545', fontWeight: '600', fontSize: '1.25rem' }}>确认删除</Modal.Title>
        </Modal.Header>
        <Modal.Body className="py-4 px-4" style={{ fontSize: '1.1rem' }}>
          <p className="mb-0">您确定要删除用户 "<strong>{currentUser?.username}</strong>" 吗？此操作不可撤销。</p>
        </Modal.Body>
        <Modal.Footer style={{ borderTop: '1px solid #e9ecef', padding: '1.25rem' }}>
          <Button 
            variant="light" 
            onClick={() => setShowDeleteModal(false)}
            style={{ fontWeight: '500', padding: '0.5rem 1.5rem', fontSize: '1rem' }}
          >
            取消
          </Button>
          <Button 
            variant="danger" 
            onClick={handleDelete}
            style={{ fontWeight: '500', padding: '0.5rem 1.5rem', fontSize: '1rem' }}
          >
            确认删除
          </Button>
        </Modal.Footer>
      </Modal>

      {/* 编辑用户对话框 */}
      <Modal show={showEditModal} onHide={() => setShowEditModal(false)} centered size="lg">
        <Modal.Header closeButton style={{ borderBottom: '1px solid #e9ecef', padding: '1.25rem' }}>
          <Modal.Title style={{ color: '#2e7d32', fontWeight: '600', fontSize: '1.25rem' }}>编辑用户</Modal.Title>
        </Modal.Header>
        <Modal.Body className="py-4 px-4">
          <Form>
            <Form.Group className="mb-4">
              <Form.Label style={{ fontWeight: '500', color: '#495057', fontSize: '1.1rem' }}>用户名</Form.Label>
              <Form.Control
                type="text"
                value={currentUser?.username || ''}
                disabled
                style={{ 
                  padding: '0.75rem 1rem',
                  borderRadius: '8px',
                  border: '1px solid #ced4da',
                  backgroundColor: '#f8f9fa',
                  fontSize: '1rem'
                }}
              />
            </Form.Group>
            
            <Form.Group className="mb-4">
              <Form.Label style={{ fontWeight: '500', color: '#495057', fontSize: '1.1rem' }}>电子邮箱</Form.Label>
              <Form.Control
                type="email"
                name="email"
                value={editForm.email}
                onChange={handleEditFormChange}
                style={{ 
                  padding: '0.75rem 1rem',
                  borderRadius: '8px',
                  border: '1px solid #ced4da',
                  fontSize: '1rem'
                }}
              />
            </Form.Group>
            
            <Form.Group className="mb-4">
              <Form.Label style={{ fontWeight: '500', color: '#495057', fontSize: '1.1rem' }}>姓名</Form.Label>
              <Form.Control
                type="text"
                name="fullName"
                value={editForm.fullName}
                onChange={handleEditFormChange}
                style={{ 
                  padding: '0.75rem 1rem',
                  borderRadius: '8px',
                  border: '1px solid #ced4da',
                  fontSize: '1rem'
                }}
              />
            </Form.Group>
            
            <Form.Group className="mb-0">
              <Form.Check
                type="checkbox"
                label="账户启用"
                name="enabled"
                checked={editForm.enabled}
                onChange={handleEditFormChange}
                style={{ fontWeight: '500', color: '#495057', fontSize: '1.1rem' }}
              />
            </Form.Group>
          </Form>
        </Modal.Body>
        <Modal.Footer style={{ borderTop: '1px solid #e9ecef', padding: '1.25rem' }}>
          <Button 
            variant="light" 
            onClick={() => setShowEditModal(false)}
            style={{ fontWeight: '500', padding: '0.5rem 1.5rem', fontSize: '1rem' }}
          >
            取消
          </Button>
          <Button 
            variant="success" 
            onClick={handleEdit}
            style={{ 
              backgroundColor: '#2e7d32',
              borderColor: '#2e7d32',
              fontWeight: '500',
              padding: '0.5rem 1.5rem',
              fontSize: '1rem'
            }}
          >
            保存更改
          </Button>
        </Modal.Footer>
      </Modal>
    </Container>
  );
};

export default AdminDashboard; 